(function (win) {

	var tvm = win.tvm = win.tvm ||
			{
				global: win
			};
	tvm.succ = 0;
	tvm.tryCount = 0;

	/*这段代码是固定的，必须要放到js中*/
	tvm.setupWebViewJavascriptBridge = function (callback) {
		if (window.WebViewJavascriptBridge) {
			return callback(WebViewJavascriptBridge);
		}
		if (window.WVJBCallbacks) {
			return window.WVJBCallbacks.push(callback);
		}
		window.WVJBCallbacks = [ callback ];
		var WVJBIframe = document.createElement('iframe');
		WVJBIframe.style.display = 'none';
		WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
		document.documentElement.appendChild(WVJBIframe);
		setTimeout(function() {
			document.documentElement.removeChild(WVJBIframe)
		}, 0)
	};

	tvm.setupWebViewJavascriptBridge(function(WebViewJavascriptBridge) {
	});

	tvm.callToDo = function (json, callback, retryTime, errorCallback){
		if(tvm.retryTime == null)
		{
			tvm.retryTime = 10;
		}
		try{
			WebViewJavascriptBridge.callHandler('callNativeToDo', json,
					function(data) {
						tvm.succ = 1;
						if(callback)
						{
							try
							{
								callback(data);


							} catch (e)
							{
								return false;
							}
						}
					})
		}
		catch(e)
		{
			tvm.tryCount++;
			setTimeout(function(){
				if(tvm.succ)
				{
					tvm.tryCount = 0;
					return true;
				}
				else if(tvm.tryCount > tvm.retryTime)
				{
					if(errorCallback)
					{
						errorCallback();
					}
					return false;
				}

				tvm.callToDo(json, callback, retryTime, errorCallback);
			}, 300);
		}
	};



	tvm.succ5 = 0;
	tvm.tryCount5 = 0;
	tvm.closeH5 = function ()
	{
		tvm.tryCount5++;
		try
		{
			WebViewJavascriptBridge.callHandler('callNativeToDo',
					{
						"action" : "close_h5",
						"data" : {
						},
						"callback" : 0
					},
					function()
					{
						tvm.succ5 = 1;
					});

		} catch (e)
		{
			setTimeout(function()
			{
				if (tvm.succ5)
				{
					tvm.tryCount5 = 0;
					return;
				} else if (tvm.tryCount5 > 3)
				{
					return;
				}
				tvm.closeH5();
			}, 300);
		}
	};

	tvm.jumpto = function(url) {
        tvm.callToDo({
            "action" : "open_url",
            "data" : {
                "url" : url
            },
            "callback" : 0
        });
    };
	tvm.getUserInfo = function() {
		return new Promise(function (reslove,reject) {
			try {
                tvm.callToDo({
                    "action" : "get_userinfo",
                    "data" : {},
                    "callback" : 1
                }, function(data) {
                    var res = JSON.parse(data);
                    reslove(res);
                }, 10, function() {
                    reject();
                });
			}catch (e){
				reject();
			}

        });
    }

})(window);

